<template>
  <div class="main">
    <todo-head @newTask='addFn' :list='list'></todo-head>
    <todo-main :list="ShowArr" @delete='delFn'></todo-main>
    <todo-foot :list="ShowArr" @changeType='typeFn' @clearEvent='clearYes'></todo-foot>
  </div>
</template>

<script>
import todoFoot from './components/TodoFoot.vue'
import todoHead from './components/TodoHead.vue'
import todoMain from './components/TodoMain.vue'
  export default {
    // 注册组件
    components:{
      todoFoot,
      todoHead,
      todoMain
    },
    data(){
      return {
        list: JSON.parse(localStorage.getItem('list') || '[]'),
        getSel:'all'
      } 
    },
    methods:{
      addFn(val){
        // 判断 计算id
        var id = this.list.length === 0 ? 100: this.list[this.list.length-1].id + 1
        this.list.push({
          id: id,
          name: val,
          isCheck:false
        })
      },
      delFn(id){
        // 删除任务
        // 找到符合条件的 同过 子组件传过来的 id
        let index = this.list.findIndex((item)=>item.id === id)
        this.list.splice(index,1)
      },
      typeFn(isSel){
        this.getSel = isSel
      },
      clearYes(){
        // 清空已完成
        this.list = this.list.filter((item)=> item.isCheck === false)
      }
    },
    computed:{
      ShowArr(){
        switch(this.getSel){
          case 'all':
            return this.list
            break
          case 'yes':
            return this.list.filter((item)=> item.isCheck === true)
            break
          case 'no':
            return this.list.filter((item)=> item.isCheck === false)
        }
      }
    },
    watch:{
      // 存储本地数据
      list:{
        deep:true,
        handler(newVal){
          localStorage.setItem('list', JSON.stringify(newVal))
        }
      }
    }
  }
</script>

<style scoped>
.main{
  margin: 100px auto;
  width: 500px;
  border: 2px solid #ccc;
  border-bottom: 0;
}
</style>